package com.liws.helloUpload.controller;

import com.liws.helloUpload.model.BaseResult;
import com.liws.helloUpload.model.PicUploadResult;
import com.liws.helloUpload.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: liweisheng
 * @Dcscription:
 * @Date: 2022/1/5 9:58
 */
@Slf4j
@RestController
public class FileUploadController {
    // 允许上传的格式 图片形式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".png"};

    @Resource
    private FileUploadService fileUploadService;

    //上传单个图片
    @PostMapping("/uploadImg")
    public BaseResult uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        boolean isFlag = false;
        for (String type : IMAGE_TYPE) {
            log.info("文件名称："+file.getOriginalFilename());
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                isFlag = true;
                break;
            }
        }

        if (isFlag) {
            PicUploadResult picUploadResult = fileUploadService.uplodadImg(file, request);
            boolean isLegal = picUploadResult.isLegal();

            if (isLegal) {

                return BaseResult.success("上传成功!!!");
            } else {
                return BaseResult.fail("图片上传有误");
            }
        } else {
            return BaseResult.fail("上传的图片格式必须为:bmp,jpg,jpeg,png");
        }

    }

    //上传多个图片
    @PostMapping("/uploadManyImg")
    public BaseResult uploadManyImg(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        boolean isFlag = false;
        for (String type : IMAGE_TYPE) {
            for (int i=0;i<files.length;i++) {
                log.info("文件名称："+files[i].getOriginalFilename());
                if (StringUtils.endsWithIgnoreCase(files[i].getOriginalFilename(), type)) {
                    isFlag = true;
                    break;
                }
            }
        }

        if (isFlag) {
            PicUploadResult picUploadResult = fileUploadService.uploadManyImg(files, request);
            boolean isLegal = picUploadResult.isLegal();

            if (isLegal) {

                return BaseResult.success("上传多个图片成功!!!");
            } else {
                return BaseResult.fail("图片上传有误");
            }
        } else {
            return BaseResult.fail("上传的图片格式必须为:bmp,jpg,jpeg,png");
        }
    }
}
